import {
    createRouter,
    createWebHashHistory
  } from "vue-router";
  import {
    ElMessage
  } from "element-plus";
  
  const routes = [{
      path: '/',
      redirect: '/login'
    },
    {
      path: "/login",
      name: "login",
      component: () =>
        import( /* webpackChunkName: "about" */ "../views/LoginPage.vue"),
    },
    {
      path: "/register",
      name: "register",
      component: () =>
        import( /* webpackChunkName: "about" */ "../views/RegisterPage.vue"),
    },
    {
      path: "/changePsw",
      name: "changePsw",
      component: () =>
        import( /* webpackChunkName: "about" */ "../views/ChangePsw.vue"),
    },
    {
      path: "/home",
      name: "home",
      component: () =>
        import( /* webpackChunkName: "about" */ "../views/HomePage.vue"),
        children:[
          {
            path: "carparkDashboard",
            name: "carparkDashboard",
            component: () =>
            import( /* webpackChunkName: "about" */ "../views/CarparkDashboard.vue"),
          },
          {
            path: "evdashboard",
            name: "evdashboard",
            component: () =>
            import( /* webpackChunkName: "about" */ "../views/Evdashboard.vue"),
          }
        ]
    },
  ];
  

  // // 路由数据存起来
  // localStorage.setItem("routers", JSON.stringify(getNav()))
  
  
  const router = createRouter({
    history: createWebHashHistory(),
    routes,
  });
  
  
  
  

  
  router.beforeEach(async (to, from, next) => {
  
    // 解决强制刷新页面，消失的问题
    if (to.matched.length == 0) {
      router.push(to.path);
    }
  
    // 获取token
    const token = localStorage.getItem("token");
    // 有token
    if (token) {
      // 添加动态路由
    //   let res = await getNav();
    //   addDynamicRoutes(res);
    if (to.path === "/login"){
      return next({
        path: "/home"
      });
    }
      next();
    } else {
      // 否则是没有
      // 如果去的是登录页
      if (to.path === "/login") {
        // 直接放行
        next();
      } else if (to.path === "/register") {
        // 直接放行
        next();
      } else {
        // 如果去的是其他页,跳转到登录页
        ElMessage({
          showClose: true,
          message: "please login",
          center: true,
        });
        // 跳转到登录页
        return next({
          path: "/login"
        });
      }
    }
  });
  
  export function addDynamicRoutes(result) {
  
    result.forEach(v => {
      router.addRoute("index", {
        path: v.path,
        name: v.name,
        meta: {
          titie: v.title
        },
        component: () => import( /* webpackChunkName: "about" */ `@/views/${v.component}`),
      })
    })
  
  }
  
  
  
  export default router;